package com.fayakeji.ucpaas;

import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author <a href="mailto:wangruihuano@gmail.com">王瑞环</a>
 * @since 1.0
 */
public class UcpaasSmsService {

    private final UcpaasProperties properties;

    public UcpaasSmsService(UcpaasProperties properties) {
        this.properties = properties;
    }

    /**
     *
     * @param templateId 模板ID
     * @param tel 电话号码
     * @param param 模板需要的参数
     * @param uid 随机码
     * @return
     */
    public UcpassSmsSingleResponse sendTemplateSms2One(String templateId, long tel, String param, String uid) {

        RestTemplate restTemplate = new RestTemplate();
        Map requsetParam = generateRequestParam(templateId, param, uid);
        requsetParam.put("mobile", String.valueOf(tel));
        return restTemplate.postForEntity(properties.getRequestUrls().getSingleSms(), requsetParam, UcpassSmsSingleResponse.class).getBody();
    }

    public UcpassSmsBatchResponse sendTemplateSms2Many(String templateId, long[] tels, String param, String uid) {

        RestTemplate restTemplate = new RestTemplate();
        if (tels == null || tels.length == 0) {
            throw new IllegalArgumentException("tels can not be null !");
        }
        Map requsetParam = generateRequestParam(templateId, param, uid);
        StringBuilder builder = new StringBuilder();
        String stringTels = Arrays.asList(tels).stream().map(String::valueOf).collect(Collectors.joining(","));
        requsetParam.put("mobile", stringTels);
        return restTemplate.postForEntity(properties.getRequestUrls().getBatchSms(), requsetParam, UcpassSmsBatchResponse.class).getBody();
    }

    private Map generateRequestParam(String templateId, String param, String uid) {
        Map<String, String> requsetParam = new HashMap(8);
        requsetParam.put("sid", properties.getSid());
        requsetParam.put("token", properties.getToken());
        requsetParam.put("appid", properties.getAppid());
        requsetParam.put("templateid", templateId);
        requsetParam.put("param", param);
        requsetParam.put("uid", uid);
        return requsetParam;
    }
}
